package admin

import (
	"context"
	"log"
	"time"

	"server-go/api/reward/internal/svc"
	"server-go/api/reward/internal/types"
	"server-go/api/reward/internal/util"
	"server-go/rpc/reward/types/reward"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.AdminLoginInput) (resp *types.AdminLoginOutput, err error) {
	out := &types.AdminLoginOutput{}
	res, rpcErr := l.svcCtx.RewardRpc.AdminLogin(l.ctx, &reward.AdminLoginInput{AdminUsername: req.AdminUsername, AdminPassword: req.AdminPassword})
	if rpcErr != nil {
		log.Println(rpcErr.Error())
		return out, nil
	}
	now := time.Now().Unix()
	token, err := util.GetJwtToken(l.svcCtx.Config.Auth.AccessSecret, req.AdminUsername, 1, now, l.svcCtx.Config.Auth.AccessExpire)
	if err != nil {
		return out, err
	}
	out.Msg = res.Msg
	out.Status = res.Status
	out.AccessToken = token
	return out, nil
}
